package com.ijmacd.footballtracker;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ImageView;

public class WelcomeActivity extends Activity {

	public static final String TAG = "Welcome Activity";
	public static final int IO_BUFFER_SIZE = 4096;
	private Bitmap mBackground;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.welcome_screen);
		Bitmap restored = (Bitmap)getLastNonConfigurationInstance();
		if(restored == null){
			new LoadBackgroundTask().execute((String[])null);
		}else{
			setBackground(restored);
		}
	}
	
	public void setBackground(Bitmap result) {
		mBackground = result;
		ImageView I = (ImageView)findViewById(R.id.frame_layout);
		I.setImageBitmap(result);
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		return mBackground;
	}

	public class LoadBackgroundTask extends AsyncTask<String, Integer, Bitmap> {
		
		static final String QUERY_URL = "http://footballtracker.co.cc/media/appbackgrounds/index.xml";
				
		@Override
		protected Bitmap doInBackground(String... params) {
			Log.d(TAG, "Downloading matches");
            //SharedPreferences settings = WelcomeActivity.this.getSharedPreferences(PREFS_NAME, 0);
	        Document doc = null;
            Bitmap bitmap = null;
            InputStream in = null;
            OutputStream out = null;
	        
	        try{
	        	String uri = QUERY_URL;// + "&since=" + settings.getInt(PREFKEY_MATCHES_UPDATED, 0);
	        	Log.d(TAG, "URI: " + uri);
	        	doc = new SAXBuilder().build(URI.create(uri).toURL());

	        	int r = (int) Math.floor(Math.random() * doc.getRootElement().getChildren("background").size());
	        	Element background = (Element)doc.getRootElement().getChildren("background").get(r);
	        	String url = background.getChild("image").getText();
	        	in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
	        	if(true){
	        		bitmap = BitmapFactory.decodeStream(in);
	        	}else{
		        	final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
	                out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
	                copy(in, out);
	                out.flush();
	                final byte[] data = dataStream.toByteArray();
	                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
	        	}

	        }catch (IOException ioe) {
	        	//Toast.makeText(TeamListActivity.this, "Invalid XML Format\n" + ioe.getMessage(), Toast.LENGTH_LONG).show();
	        	Log.e(TAG + " IOException", "Error: " + ioe.getMessage());
	        	ioe.printStackTrace();
	        } catch (RuntimeException re) {
	        	//Toast.makeText(TeamListActivity.this, "XML Format Error\n" + re.getMessage(), Toast.LENGTH_LONG).show();
	        	Log.e(TAG + " RuntimeException", "Error: " + re.getMessage());
	        	re.printStackTrace();
	        } catch (Exception ex){
	        	//Toast.makeText(this, "Real error\n" + ex.getMessage(), Toast.LENGTH_LONG).show();
	        	Log.e(TAG + " Exception", "Real Error: " + ex.getMessage());
	        }
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			setBackground(result);
		}
	}
		/**
	     * Copy the content of the input stream into the output stream, using a temporary
	     * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
	     *
	     * @param in The input stream to copy from.
	     * @param out The output stream to copy to.
	     *
	     * @throws IOException If any error occurs during the copy.
	     */
	    private void copy(InputStream in, OutputStream out) throws IOException {
	        byte[] b = new byte[IO_BUFFER_SIZE];
	        int read;
	        while ((read = in.read(b)) != -1) {
	            out.write(b, 0, read);
	        }
	    }
}
